<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设备管理 - 宠物视频控制台</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/fonts.css') }}">
    <link rel="stylesheet" href="{{ url_for('static', filename='css/fontawesome.min.css') }}">
    <script src="{{ url_for('static', filename='js/tailwind.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/auth.js') }}"></script>
    <script src="{{ url_for('static', filename='js/socket.io.min.js') }}"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#FF6B35',
                        secondary: '#FFB800'
                    },
                    borderRadius: {
                        'button': '4px'
                    }
                }
            }
        }
    </script>
    <style>
        body {
            min-height: 1024px;
            background-color: #F8F9FA;
        }
        .glass-effect {
            backdrop-filter: blur(10px);
            background-color: rgba(255, 255, 255, 0.8);
        }
        .device-card:hover {
            transform: translateY(-2px);
            transition: all 0.3s ease;
        }
        .range-slider {
            -webkit-appearance: none;
            appearance: none;
            height: 6px;
            border-radius: 3px;
            background: #e5e7eb;
            outline: none;
        }
        .range-slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background: #FF6B35;
            cursor: pointer;
        }
        .range-slider::-moz-range-thumb {
            width: 18px;
            height: 18px;
            border-radius: 50%;
            background: #FF6B35;
            cursor: pointer;
            border: none;
        }
        
        /* 设备状态切换动画 */
        .device-status-transition {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .control-panel-enter {
            opacity: 0;
            transform: translateY(10px);
        }
        
        .control-panel-enter-active {
            opacity: 1;
            transform: translateY(0);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        .control-panel-exit {
            opacity: 1;
            transform: translateY(0);
        }
        
        .control-panel-exit-active {
            opacity: 0;
            transform: translateY(10px);
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        
        /* 离线状态滑块样式 */
        .range-slider:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .range-slider:disabled::-webkit-slider-thumb {
            background: #9CA3AF;
        }
        
        .range-slider:disabled::-moz-range-thumb {
            background: #9CA3AF;
        }
        /* Toast 通知动画 */
        .toast-message {
            opacity: 0;
            transform: translateY(-20px);
            box-shadow: 0 4px 24px 0 rgba(0,0,0,0.08);
        }
        .toast-success {
            background: #E6F9EC;
            color: #1A7F4F;
            border: 1px solid #B7EBD3;
        }
        .toast-error {
            background: #FDEAEA;
            color: #B91C1C;
            border: 1px solid #F9C0C0;
        }
    </style>
</head>
<body class="bg-gray-50">
    <nav class="fixed top-0 left-0 right-0 z-50 glass-effect border-b border-gray-200">
        <div class="max-w-[1440px] mx-auto px-8 h-16 flex items-center justify-between">
            <div class="flex items-center gap-8">
                <a href="/" class="text-2xl font-['Pacifico'] text-primary">logo</a>
                <div class="relative">
                    <form action="/search" method="GET" class="flex">
                        <input type="text" name="q" placeholder="搜索视频、直播或设备" 
                               class="w-[400px] h-10 pl-10 pr-4 rounded-full bg-gray-100 border-none focus:outline-none focus:ring-2 focus:ring-primary/20 text-sm">
                        <button type="submit" class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400">
                            <i class="fas fa-search"></i>
                        </button>
                    </form>
                </div>
            </div>
            <div class="flex items-center gap-6">
                <a href="{{ url_for('pages.devices_page') }}" class="flex items-center gap-2 text-primary !rounded-button">
                    <i class="fas fa-tv text-lg"></i>
                    <span class="whitespace-nowrap">我的设备</span>
                </a>
                {% if user %}
                    <a href="{{ url_for('pages.messages_page') }}" class="flex items-center gap-2 text-gray-600 hover:text-primary !rounded-button">
                        <i class="fas fa-bell text-lg"></i>
                        <span class="whitespace-nowrap">消息</span>
                        {% if unread_count > 0 %}
                            <span class="bg-red-500 text-white text-xs rounded-full px-2 py-1">{{ unread_count }}</span>
                        {% endif %}
                    </a>
                {% endif %}
                {% if user %}
                    <div class="flex items-center gap-3">
                        <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
                            <i class="fas fa-user text-primary"></i>
                        </div>
                        <span class="text-sm text-gray-700">{{ user.username }}</span>
                        <button onclick="logout()" class="text-gray-500 hover:text-primary text-sm">
                            <i class="fas fa-sign-out-alt"></i>
                        </button>
                    </div>
                {% else %}
                    <div class="flex items-center gap-3">
                        <div class="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                            <i class="fas fa-user text-gray-600"></i>
                        </div>
                        <a href="{{ url_for('pages.login_page') }}" class="text-gray-600 hover:text-primary text-sm">登录</a>
                        <a href="{{ url_for('pages.register_page') }}" class="text-gray-600 hover:text-primary text-sm">注册</a>
                    </div>
                {% endif %}
            </div>
        </div>
    </nav>

    <main class="max-w-[1440px] mx-auto pt-24 px-8">
        <!-- 页面头部 -->
        <section class="mb-8">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <h1 class="text-3xl font-bold text-gray-800 mb-2">设备管理</h1>
                    <p class="text-gray-600">管理您的智能设备，为宠物提供更好的视听体验</p>
                </div>
                <a href="{{ url_for('pages.add_device_page') }}" class="px-6 py-3 bg-primary text-white font-medium rounded-lg hover:bg-primary/90 transition-colors">
                    <i class="fas fa-plus mr-2"></i>
                    添加设备
                </a>
            </div>

            <!-- 设备统计 -->
            <div class="grid grid-cols-4 gap-6 mb-8">
                <div class="bg-white p-6 rounded-xl shadow-sm">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-500">总设备数</p>
                            <p class="text-2xl font-bold text-gray-800" id="total-devices">{{ devices|length }}</p>
                        </div>
                        <div class="w-12 h-12 rounded-xl bg-blue-100 flex items-center justify-center">
                            <i class="fas fa-tv text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white p-6 rounded-xl shadow-sm">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-500">在线设备</p>
                            <p class="text-2xl font-bold text-green-600" id="online-devices">
                                {% set online_count = 0 %}
                                {% for device in devices %}
                                    {% set real_time_status = device[8] if device|length > 8 else {'online': False} %}
                                    {% if real_time_status is mapping and real_time_status.get('online', False) or device[5] == 'online' %}
                                        {% set online_count = online_count + 1 %}
                                    {% endif %}
                                {% endfor %}
                                {{ online_count }}
                            </p>
                        </div>
                        <div class="w-12 h-12 rounded-xl bg-green-100 flex items-center justify-center">
                            <i class="fas fa-wifi text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white p-6 rounded-xl shadow-sm">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-500">离线设备</p>
                            <p class="text-2xl font-bold text-red-600" id="offline-devices">
                                {% set offline_count = 0 %}
                                {% for device in devices %}
                                    {% set real_time_status = device[8] if device|length > 8 else {'online': False} %}
                                    {% if not (real_time_status is mapping and real_time_status.get('online', False) or device[5] == 'online') %}
                                        {% set offline_count = offline_count + 1 %}
                                    {% endif %}
                                {% endfor %}
                                {{ offline_count }}
                            </p>
                        </div>
                        <div class="w-12 h-12 rounded-xl bg-red-100 flex items-center justify-center">
                            <i class="fas fa-power-off text-red-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white p-6 rounded-xl shadow-sm">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-500">设备类型</p>
                            <p class="text-2xl font-bold text-purple-600">{{ devices|map(attribute='4')|unique|list|length }}</p>
                        </div>
                        <div class="w-12 h-12 rounded-xl bg-purple-100 flex items-center justify-center">
                            <i class="fas fa-layer-group text-purple-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <!-- 设备列表 -->
        <section class="mb-8">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-xl font-bold">我的设备</h2>
                <div class="flex items-center gap-4">
                    <button class="px-4 py-2 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors">
                        <i class="fas fa-sort mr-2"></i>
                        排序
                    </button>
                    <button class="px-4 py-2 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 transition-colors">
                        <i class="fas fa-filter mr-2"></i>
                        筛选
                    </button>
                </div>
            </div>

            {% if devices %}
                <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {% for device in devices %}
                    <div class="device-card bg-white rounded-xl shadow-sm hover:shadow-md transition-all duration-300 p-6" data-device-id="{{ device.device_id }}" data-device-name="{{ device.name }}" data-device-raw-id="{{ device.device_id }}">
                        <div class="flex items-start justify-between mb-4">
                            <div class="flex items-center gap-3">
                                <div class="w-12 h-12 rounded-xl bg-gray-100 flex items-center justify-center">
                                    <i class="fas fa-power-off text-gray-400 text-xl"></i>
                                </div>
                                <div>
                                    <div class="device-name flex items-center gap-2" data-device-id="{{ device.device_id }}" data-device-name="{{ device.name }}">
                                        <span class="name-display font-medium text-gray-800">{{ device.name }}</span>
                                        <button class="edit-name-btn opacity-0 transition-opacity text-gray-400 hover:text-primary">
                                            <i class="fas fa-edit text-sm"></i>
                                        </button>
                                    </div>
                                    <p class="text-sm text-gray-500">{{ device.device_name }}</p>
                                </div>
                            </div>
                            <div class="flex items-center gap-2">
                                <button onclick="deleteDevice('{{ device.device_id }}', '{{ device.name }}', '{{ device.device_type }}')" 
                                        class="text-gray-400 hover:text-red-500 transition-colors">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </div>
                        <div class="space-y-4 device-status-transition">
                            <div class="text-center py-4">
                                <p class="text-sm text-gray-500">设备离线</p>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            {% else %}
                <div class="text-center py-12">
                    <div class="w-24 h-24 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-tv text-3xl text-gray-400"></i>
                    </div>
                    <h3 class="text-xl font-medium text-gray-600 mb-2">暂无设备</h3>
                    <p class="text-gray-500 mb-6">您还没有添加任何设备</p>
                    <a href="{{ url_for('pages.add_device_page') }}" class="px-6 py-3 bg-primary text-white font-medium rounded-lg hover:bg-primary/90 transition-colors">
                        <i class="fas fa-plus mr-2"></i>
                        添加第一个设备
                    </a>
                </div>
            {% endif %}
        </section>

        <!-- 快速操作 -->
        <section class="mb-8">
            <h2 class="text-xl font-bold mb-6">快速操作</h2>
            <div class="grid grid-cols-3 gap-6">
                <div class="bg-white p-6 rounded-xl shadow-sm hover:shadow-md cursor-pointer">
                    <div class="text-center">
                        <div class="w-16 h-16 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-broadcast-tower text-blue-600 text-2xl"></i>
                        </div>
                        <h3 class="font-medium mb-2">批量播放</h3>
                        <p class="text-sm text-gray-500">在所有在线设备上播放视频</p>
                    </div>
                </div>
                <div class="bg-white p-6 rounded-xl shadow-sm hover:shadow-md cursor-pointer">
                    <div class="text-center">
                        <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-volume-up text-green-600 text-2xl"></i>
                        </div>
                        <h3 class="font-medium mb-2">音量调节</h3>
                        <p class="text-sm text-gray-500">统一调节所有设备音量</p>
                    </div>
                </div>
                <div class="bg-white p-6 rounded-xl shadow-sm hover:shadow-md cursor-pointer">
                    <div class="text-center">
                        <div class="w-16 h-16 bg-orange-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-chart-line text-orange-600 text-2xl"></i>
                        </div>
                        <h3 class="font-medium mb-2">使用统计</h3>
                        <p class="text-sm text-gray-500">查看设备使用情况</p>
                    </div>
                </div>
            </div>
        </section>
    </main>

    <!-- 悬浮Toast通知系统 -->
    <div id="toast-container" class="fixed top-6 left-1/2 z-50 space-y-2" style="transform: translateX(-50%);"></div>

    <!-- 删除确认弹窗 -->
    <div id="deleteModal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden flex items-center justify-center">
        <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full mx-4 transform transition-all duration-300 scale-95 opacity-0" id="deleteModalContent">
            <div class="p-8">
                <!-- 图标 -->
                <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-6">
                    <i class="fas fa-exclamation-triangle text-red-500 text-2xl"></i>
                </div>
                
                <!-- 标题 -->
                <h3 class="text-xl font-bold text-gray-800 text-center mb-2">确认删除设备？</h3>
                
                <!-- 设备信息 -->
                <div class="bg-gray-50 rounded-lg p-4 mb-6">
                    <div class="flex items-center gap-3">
                        <div class="w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center">
                            <i class="fas fa-tv text-primary"></i>
                        </div>
                        <div>
                            <p class="font-medium text-gray-800" id="deleteDeviceName">设备名称</p>
                            <p class="text-sm text-gray-500" id="deleteDeviceType">设备类型</p>
                        </div>
                    </div>
                </div>
                
                <!-- 警告信息 -->
                <div class="bg-orange-50 border border-orange-200 rounded-lg p-4 mb-6">
                    <div class="flex items-start gap-3">
                        <i class="fas fa-info-circle text-orange-500 mt-0.5"></i>
                        <div>
                            <p class="text-sm text-orange-700 font-medium mb-1">删除后无法恢复</p>
                            <p class="text-xs text-orange-600">此操作将永久删除该设备及其所有设置，请谨慎操作。</p>
                        </div>
                    </div>
                </div>
                
                <!-- 按钮组 -->
                <div class="flex gap-3">
                    <button onclick="closeDeleteModal()" 
                            class="flex-1 px-4 py-3 bg-gray-100 text-gray-700 font-medium rounded-lg hover:bg-gray-200 transition-colors">
                        取消
                    </button>
                    <button onclick="confirmDeleteDevice()" 
                            class="flex-1 px-4 py-3 bg-red-500 text-white font-medium rounded-lg hover:bg-red-600 transition-colors">
                        <i class="fas fa-trash mr-2"></i>
                        删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <footer class="bg-white border-t border-gray-200 mt-12">
        <div class="max-w-[1440px] mx-auto px-8 py-12">
            <div class="grid grid-cols-4 gap-8 mb-8">
                <div>
                    <h3 class="text-xl font-['Pacifico'] text-primary mb-4">logo</h3>
                    <p class="text-gray-500 text-sm">让宠物的生活更有趣，让主人更放心。我们致力于为您的宠物提供最优质的视听体验。</p>
                </div>
                <div>
                    <h4 class="font-medium mb-4">快速链接</h4>
                    <ul class="space-y-2 text-sm text-gray-500">
                        <li><a href="/" class="hover:text-primary">首页</a></li>
                        <li><a href="{{ url_for('pages.video_list') }}" class="hover:text-primary">视频库</a></li>
                        <li><a href="#" class="hover:text-primary">直播频道</a></li>
                        <li><a href="{{ url_for('pages.devices_page') }}" class="hover:text-primary">设备管理</a></li>
                    </ul>
                </div>
                <div>
                    <h4 class="font-medium mb-4">帮助中心</h4>
                    <ul class="space-y-2 text-sm text-gray-500">
                        <li><a href="#" class="hover:text-primary">使用指南</a></li>
                        <li><a href="#" class="hover:text-primary">常见问题</a></li>
                        <li><a href="#" class="hover:text-primary">联系我们</a></li>
                        <li><a href="#" class="hover:text-primary">意见反馈</a></li>
                    </ul>
                </div>
                <div>
                    <h4 class="font-medium mb-4">关注我们</h4>
                    <div class="flex gap-4">
                        <a href="#" class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-primary hover:text-white">
                            <i class="fab fa-weixin"></i>
                        </a>
                        <a href="#" class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-primary hover:text-white">
                            <i class="fab fa-weibo"></i>
                        </a>
                        <a href="#" class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center text-gray-500 hover:bg-primary hover:text-white">
                            <i class="fab fa-wechat"></i>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </footer>

    <script>
        // Toast通知
        function showMessage(message, type = 'info') {
            const toastContainer = document.getElementById('toast-container');
            if (!toastContainer) return;
            
            const toast = document.createElement('div');
            toast.className = `flex items-center px-6 py-3 rounded-lg shadow-lg text-base font-medium transition-all duration-300 opacity-0 pointer-events-auto toast-message ${
                type === 'success' ? 'toast-success' : 
                type === 'error' ? 'toast-error' : 
                'bg-blue-100 text-blue-800 border border-blue-200'
            }`;
            toast.style.minWidth = '220px';
            toast.style.maxWidth = '400px';
            toast.style.marginTop = '8px';
            toast.innerHTML = `
                <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'} mr-3 text-xl"></i>
                <span>${message}</span>
            `;
            toastContainer.appendChild(toast);
            
            setTimeout(() => {
                toast.style.opacity = '1';
                toast.style.transform = 'translateY(0)';
            }, 10);
            
            setTimeout(() => {
                toast.style.opacity = '0';
                toast.style.transform = 'translateY(-20px)';
                setTimeout(() => {
                    toast.remove();
                }, 300);
            }, 2500);
        }
        
        // 登出函数
        async function logout() {
            try {
                await jwtAuth.logout();
            } catch (error) {
                console.error('登出失败:', error);
                window.location.href = '/';
            }
        }
        
        // 全局变量存储要删除的设备信息
        let deviceToDelete = null;
        
        // 显示删除确认弹窗
        function showDeleteModal(deviceId, deviceName, deviceType) {
            deviceToDelete = { device_id: deviceId, name: deviceName, type: deviceType };
            
            document.getElementById('deleteDeviceName').textContent = deviceName;
            document.getElementById('deleteDeviceType').textContent = deviceType;
            
            const modal = document.getElementById('deleteModal');
            const modalContent = document.getElementById('deleteModalContent');
            
            modal.classList.remove('hidden');
            
            setTimeout(() => {
                modalContent.classList.remove('scale-95', 'opacity-0');
                modalContent.classList.add('scale-100', 'opacity-100');
            }, 10);
        }
        
        // 关闭删除确认弹窗
        function closeDeleteModal() {
            const modal = document.getElementById('deleteModal');
            const modalContent = document.getElementById('deleteModalContent');
            
            modalContent.classList.remove('scale-100', 'opacity-100');
            modalContent.classList.add('scale-95', 'opacity-0');
            
            setTimeout(() => {
                modal.classList.add('hidden');
                deviceToDelete = null;
            }, 300);
        }
        
        // 确认删除设备
        async function confirmDeleteDevice() {
            if (!deviceToDelete) {
                closeDeleteModal();
                return;
            }
            
            try {
                console.log('删除设备:', deviceToDelete.device_id);
                const response = await jwtAuth.authenticatedRequest(`/api/v1/devices/${deviceToDelete.device_id}`, {
                    method: 'DELETE'
                });
                
                console.log('删除设备响应:', response);
                if (response.ok) {
                    showMessage('设备删除成功');
                    closeDeleteModal();
                    setTimeout(() => {
                        window.location.reload();
                    }, 1000);
                } else {
                    const data = await response.json();
                    // 优先展示message字段，其次error字段
                    showMessage(data.message || data.error || '设备删除失败', 'error');
                    closeDeleteModal();
                }
            } catch (error) {
                console.error('删除设备错误:', error);
                showMessage('网络错误，请重试', 'error');
                closeDeleteModal();
            }
        }
        
        // 删除设备（触发弹窗）
        function deleteDevice(deviceId, deviceName, deviceType) {
            showDeleteModal(deviceId, deviceName, deviceType);
        }
        
        // 初始化Socket.IO连接
        let socket = null;
        function initSocketIO() {
            const accessToken = getCookie('access_token') || localStorage.getItem('access_token');
            if (!accessToken) return;
            
            // 连接Socket.IO
            socket = io();
            
            // 连接成功事件
            socket.on('connect', function() {
                console.log('Socket.IO连接成功');
                
                // 加入用户房间
                const user_id = '{{ user_id }}';
                if (user_id) {
                    socket.emit('join_user_room', { user_id: user_id });
                }
            });
            
            // 设备状态变化事件
            socket.on('device_status_changed', function(data) {
                console.log('设备状态变化:', data);
                const { device_id, status } = data;
                updateDeviceStatus(device_id, status);
            });
            
            // 设备上线事件
            socket.on('device_online', function(data) {
                console.log('设备上线:', data);
                const { device_id } = data;
                updateDeviceStatus(device_id, 'online');
            });
            
            // 设备离线事件
            socket.on('device_offline', function(data) {
                console.log('设备离线:', data);
                const { device_id } = data;
                updateDeviceStatus(device_id, 'offline');
            });
            
            // 认证成功事件
            socket.on('authenticated', function(data) {
                console.log('认证成功:', data);
            });
            
            // 加入用户房间成功事件
            socket.on('joined_user_room', function(data) {
                console.log('成功加入用户房间:', data);
            });
            
            // 错误事件
            socket.on('error', function(data) {
                console.error('Socket.IO错误:', data);
                showMessage(data.message || '连接错误', 'error');
            });
            
            // 定期刷新设备状态
            setInterval(refreshDeviceStatus, 30000); // 每30秒刷新一次
        }
        
        // 更新设备状态显示
        function updateDeviceStatus(deviceId, status, isPlaying) {
            const deviceCard = document.querySelector(`[data-device-id="${deviceId}"]`);
            if (!deviceCard) return;
            
            const deviceIcon = deviceCard.querySelector('.w-12.h-12 i');
            const iconContainer = deviceCard.querySelector('.w-12.h-12');
            
            // 判断设备是否在线（支持多种状态值）
            const isOnline = status === 'online' || status === true || status === 'true';
            
            // 检查当前状态是否已经是指定状态
            const currentIsOnline = deviceIcon && deviceIcon.classList.contains('fa-tv') && deviceIcon.classList.contains('text-primary');
            const statusChanged = currentIsOnline !== isOnline;
            
            if (isOnline) {
                // 设备在线
                if (deviceIcon) {
                    deviceIcon.className = 'fas fa-tv text-primary text-xl device-status-transition';
                }
                if (iconContainer) {
                    iconContainer.className = 'w-12 h-12 rounded-xl bg-primary/10 flex items-center justify-center device-status-transition';
                }
                
                // 显示在线控制面板
                const controlPanel = deviceCard.querySelector('.space-y-4');
                if (controlPanel) {
                    controlPanel.innerHTML = `
                        <div>
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm text-gray-600">音量</span>
                                <span class="text-sm text-gray-600">65%</span>
                            </div>
                            <input type="range" class="range-slider w-full" value="65" min="0" max="100">
                        </div>
                        <div>
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm text-gray-600">亮度</span>
                                <span class="text-sm text-gray-600">80%</span>
                            </div>
                            <input type="range" class="range-slider w-full" value="80" min="0" max="100">
                        </div>
                        <div class="flex gap-2 pt-2">
                            <button class="flex-1 px-3 py-2 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 text-sm play-toggle-btn">
                                <i class="fas ${isPlaying ? 'fa-pause' : 'fa-play'} mr-1"></i>
                                ${isPlaying ? '暂停' : '播放'}
                            </button>
                            <button class="flex-1 px-3 py-2 bg-gray-100 text-gray-600 rounded-lg hover:bg-gray-200 text-sm">
                                <i class="fas fa-cog mr-1"></i>
                                设置
                            </button>
                        </div>
                    `;
                }
                
                // 初始化控制按钮
                initControlButtons(deviceCard, deviceId, isPlaying);
                
                // 只在状态变化时显示通知
                if (statusChanged) {
                    showMessage('设备已上线', 'success');
                }
            } else {
                // 设备离线
                if (deviceIcon) {
                    deviceIcon.className = 'fas fa-power-off text-gray-400 text-xl device-status-transition';
                }
                if (iconContainer) {
                    iconContainer.className = 'w-12 h-12 rounded-xl bg-gray-100 flex items-center justify-center device-status-transition';
                }
                
                // 显示离线控制面板
                const controlPanel = deviceCard.querySelector('.space-y-4');
                if (controlPanel) {
                    controlPanel.innerHTML = `
                        <div>
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm text-gray-400">音量</span>
                                <span class="text-sm text-gray-400">0%</span>
                            </div>
                            <input type="range" class="range-slider w-full opacity-50 cursor-not-allowed" value="0" min="0" max="100" disabled>
                        </div>
                        <div>
                            <div class="flex items-center justify-between mb-2">
                                <span class="text-sm text-gray-400">亮度</span>
                                <span class="text-sm text-gray-400">0%</span>
                            </div>
                            <input type="range" class="range-slider w-full opacity-50 cursor-not-allowed" value="0" min="0" max="100" disabled>
                        </div>
                        <div class="text-center py-4">
                            <p class="text-sm text-gray-500">设备离线</p>
                        </div>
                    `;
                }
                
                // 只在状态变化时显示通知
                if (statusChanged) {
                    showMessage('设备已离线', 'error');
                }
            }
            
            // 更新统计数字
            updateDeviceStats();
        }
        
        // 更新设备统计数字
        function updateDeviceStats() {
            const deviceCards = document.querySelectorAll('.device-card');
            let onlineCount = 0;
            let offlineCount = 0;
            
            deviceCards.forEach(card => {
                const deviceIcon = card.querySelector('.w-12.h-12 i');
                if (deviceIcon && deviceIcon.classList.contains('fa-tv') && deviceIcon.classList.contains('text-primary')) {
                    onlineCount++;
                } else {
                    offlineCount++;
                }
            });
            
            const totalDevices = document.getElementById('total-devices');
            const onlineDevices = document.getElementById('online-devices');
            const offlineDevices = document.getElementById('offline-devices');
            
            if (totalDevices) totalDevices.textContent = deviceCards.length;
            if (onlineDevices) onlineDevices.textContent = onlineCount;
            if (offlineDevices) offlineDevices.textContent = offlineCount;
        }
        
        // 获取Cookie函数
        function getCookie(name) {
            const value = `; ${document.cookie}`;
            const parts = value.split(`; ${name}=`);
            if (parts.length === 2) return parts.pop().split(';').shift();
            return null;
        }
        
        // 初始化设备名称编辑功能
        function initDeviceNameEditing() {
            const deviceCards = document.querySelectorAll('.device-card');
            deviceCards.forEach(card => {
                const nameDisplay = card.querySelector('.name-display');
                const editBtn = card.querySelector('.edit-name-btn');
                
                if (nameDisplay && editBtn) {
                    // 悬停时显示编辑按钮
                    card.addEventListener('mouseenter', () => {
                        editBtn.style.opacity = '1';
                    });
                    
                    card.addEventListener('mouseleave', () => {
                        editBtn.style.opacity = '0';
                    });
                    
                    // 点击编辑按钮
                    editBtn.addEventListener('click', () => {
                        const deviceId = card.dataset.deviceId;
                        const currentName = nameDisplay.textContent;
                        
                        // 创建输入框
                        const input = document.createElement('input');
                        input.type = 'text';
                        input.value = currentName;
                        input.className = 'font-medium text-gray-800 bg-transparent border-b border-primary focus:outline-none focus:border-primary/50';
                        
                        // 替换显示文本
                        nameDisplay.textContent = '';
                        nameDisplay.appendChild(input);
                        input.focus();
                        
                        // 处理保存
                        const saveName = () => {
                            const newName = input.value.trim();
                            if (newName && newName !== currentName) {
                                updateDeviceName(deviceId, newName);
                            }
                            nameDisplay.textContent = newName || currentName;
                        };
                        
                        // 处理取消
                        const cancelEdit = () => {
                            nameDisplay.textContent = currentName;
                        };
                        
                        // 事件监听
                        input.addEventListener('blur', saveName);
                        input.addEventListener('keydown', (e) => {
                            if (e.key === 'Enter') {
                                saveName();
                            } else if (e.key === 'Escape') {
                                cancelEdit();
                            }
                        });
                    });
                }
            });
        }
        
        // 初始化设备卡片悬停效果
        function initDeviceCardHover() {
            const deviceCards = document.querySelectorAll('.device-card');
            deviceCards.forEach(card => {
                card.addEventListener('mouseenter', () => {
                    card.style.transform = 'translateY(-2px)';
                });
                
                card.addEventListener('mouseleave', () => {
                    card.style.transform = 'translateY(0)';
                });
            });
        }
        
        // 初始化删除确认弹窗
        function initDeleteModal() {
            const deleteModal = document.getElementById('deleteModal');
            
            // 点击背景关闭弹窗
            deleteModal.addEventListener('click', function(e) {
                if (e.target === deleteModal) {
                    closeDeleteModal();
                }
            });
            
            // ESC键关闭弹窗
            document.addEventListener('keydown', function(e) {
                if (e.key === 'Escape' && !deleteModal.classList.contains('hidden')) {
                    closeDeleteModal();
                }
            });
        }
        
        // 初始化Toast通知系统
        function initToastSystem() {
            // Toast系统已在showMessage函数中实现
        }
        
        // 更新设备名称
        function updateDeviceName(deviceId, newName) {
            const accessToken = getCookie('access_token') || localStorage.getItem('access_token');
            if (!accessToken) {
                showMessage('请先登录', 'error');
                return;
            }
            
            fetch(`/api/v1/devices/${deviceId}/name`, {
                method: 'PUT',
                headers: {
                    'Authorization': `Bearer ${accessToken}`,
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name: newName })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showMessage('设备名称更新成功', 'success');
                } else {
                    showMessage(data.message || data.error || '设备名称更新失败', 'error');
                }
            })
            .catch(error => {
                console.error('更新设备名称失败:', error);
                showMessage('设备名称更新失败', 'error');
            });
        }

        // Restore the entire refreshDeviceStatus function
        function refreshDeviceStatus() {
            const accessToken = getCookie('access_token') || localStorage.getItem('access_token');
            if (!accessToken) return;
            
            fetch('/api/v1/devices/status', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${accessToken}`,
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    data.data.forEach(device => {
                        // 直接用status字段判断设备状态
                        updateDeviceStatus(device.device_id, device.status);
                    });
                }
            })
            .catch(error => {
                console.error('获取设备状态失败:', error);
                showMessage('获取设备状态失败', 'error');
            });
        }

        // 函数定义
        function initControlButtons(card, deviceId, isPlayingInit) {
            const playToggleBtn = card.querySelector('.play-toggle-btn');
            if (playToggleBtn) {
                let isPlaying = !!isPlayingInit;
                playToggleBtn.innerHTML = `<i class="fas ${isPlaying ? 'fa-pause' : 'fa-play'} mr-1"></i> ${isPlaying ? '暂停' : '播放'}`;
                playToggleBtn.addEventListener('click', () => {
                    if (isPlaying) {
                        socket.emit('player_control', { device_id: deviceId, action: 'pause' });
                        showMessage('发送暂停命令');
                        playToggleBtn.innerHTML = '<i class="fas fa-play mr-1"></i> 播放';
                    } else {
                        socket.emit('player_control', { device_id: deviceId, action: 'play' });
                        showMessage('发送播放命令');
                        playToggleBtn.innerHTML = '<i class="fas fa-pause mr-1"></i> 暂停';
                    }
                    isPlaying = !isPlaying;
                });
            }
        }

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('设备管理页面初始化');
            
            // 初始化Socket.IO连接
            initSocketIO();
            
            // 初始化设备名称编辑功能
            initDeviceNameEditing();
            
            // 初始化设备卡片悬停效果
            initDeviceCardHover();
            
            // 初始化删除确认弹窗
            initDeleteModal();
            
            // 初始化Toast通知系统
            initToastSystem();
            
            // 页面加载时立即刷新一次设备状态
            setTimeout(refreshDeviceStatus, 1000);
            
            // 定期刷新设备状态（每30秒）
            setInterval(refreshDeviceStatus, 30000); // 每30秒刷新一次
        });
    </script>
</body>
</html> 